<?php

namespace app\models;

use app\components\BaseActiveRecord;
use app\helpers\EncryptHelper;
use Yii;
use yii\helpers\Url;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "{{%admin}}".
 *
 * @property int $id
 * @property int $gid
 * @property string $username
 * @property string $password
 * @property int $status
 * @property int $create_time
 */
class Admin extends BaseActiveRecord implements IdentityInterface {

    const rememberTime = 3600;

    const GROUP_ADMIN = 1;

    const STATUS_ACTIVE = 1;
    const STATUS_DISABLED = 2;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%admin}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['gid', 'status', 'create_time'], 'integer'],
            [['username'], 'string', 'max' => 120],
            [['password'], 'string', 'max' => 32],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'gid' => 'Gid',
            'username' => 'Username',
            'password' => 'Password',
            'status' => 'Status',
            'create_time' => 'Create Time',
        ];
    }

    public static function findIdentity($id) {
        return self::findOne($id);
    }

    public static function findIdentityByAccessToken($token, $type = null) {
    }

    /**
     * Returns an ID that can uniquely identify a user identity.
     * @return string|int an ID that uniquely identifies a user identity.
     */
    public function getId() {
        return $this->id;
    }

    public function getAuthKey() {
        return EncryptHelper::md5(APP_KEY);
    }

    public function validateAuthKey($authKey) {
        return EncryptHelper::md5(APP_KEY) === $authKey;
    }

    public function isActive() {
        return intval($this->status) === self::YES;
    }

    public function login() {
        if (!$this->validate()) {
            return static::retErr($this->getError());
        }

        $user = static::findOne(['username' => $this->username]);
        if (!$user) {
            return static::retErr(Yii::t('app', 'Username or password is incorrect.'));
        }
        $_pass = EncryptHelper::md5($this->password);
        if ($_pass !== $user['password']) {
            return static::retErr(Yii::t('app', 'Username or password is incorrect.'), 1, [$_pass, $user->password, APP_KEY]);
        }

        if (!$user->isActive()) {
            return static::retErr(Yii::t('app', 'Account is disabled.'));
        }

        $this->id = $user->id;

        Yii::$app->user->login($user, self::rememberTime);

        $res = static::retOK();
        $res['redirect'] = Url::to(['user/']);
        return $res;
    }
}
